/**
 * Created by yangbo on 2017/7/13.
 */

$(document).ready(function () {


})


function addProduct(obj){
    /**
     * shopCart = [{"prodId":1,"num":5},
     * {"prodId":2,"num":6}
     *  ]
     */
    var shopCart = $.cookie("shopcart");
    if(shopCart == null){
        shopCart = [];
    }else {
        shopCart = JSON.parse(shopCart);
    }

    var current_id = obj.parent().find('.productId').val();
    var current_num = 0;
    var flag = false;

    for(var i = 0; i < shopCart.length; i++){
        if(shopCart[i].prodId == current_id){
            current_num = ++shopCart[i].num;
            flag = true;                    // 表示以前添加过该商品
        }
    }

    if(flag == false){
        // 创建购物车信息
        current_num++;
        var current_product = {"prodId":current_id,"num":current_num};
        shopCart.push(current_product);     // 新的商品添加
    }

    obj.parent().find('.shopCount').text(current_num);
    $.cookie("shopcart",JSON.stringify(shopCart));

    console.log(JSON.stringify(shopCart));


}

function minusProduct(obj){
    var current_id = obj.parent().find('.productId').val();
    var current_num = parseInt(obj.parent().find('.shopCount').text());

    if(current_num <= 0){
        return;
    }
    current_num--;      // 加一个
    // 创建购物车信息
    var current_product = {"prodId":current_id,"num":current_num};
    obj.parent().find('.shopCount').text(current_num);

}
